package thread;

public class SyncDemo1 {
    static boolean success1 = false;//表示第一个人是否取款成功
    static boolean success2 = false;//表示第二个人是否取款成功

    public static void main(String[] args) throws InterruptedException {
        Bank bank = new Bank();
        int sum = 0;
        while (true) {
            ++sum;
            //Target type of a lambda conversion must be an interface
//            Thread t1 = ()->{success1 = bank.getMoney(20000);};
            Thread t1 = new Thread() {
                public void run() {
                    success1 = bank.getMoney(20000);
                }
            };

            Thread t2 = new Thread() {
                public void run() {
                    success2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();

            Thread.sleep(10);//阻塞主线程一段时间，用于让t1，t2线程执行完毕
            if (success1 && success2) {
                System.out.println("取款成功" + sum + "次");
                break;
            } else {
                success1 = false;
                success2 = false;
                bank.saveAccount(20000);
            }
        }

    }
}

class Bank {
    private int account = 20000;

    public synchronized boolean getMoney(int money) {
        int account = getAccount();
        if (account >= money) {
            account -= money;
            Thread.yield();
            saveAccount(account);
            return true;
        } else {
            return false;
        }
    }

    public int getAccount() {
        return account;
    }

    public void saveAccount(int account) {
        this.account = account;
    }
}